/**
 * Copyright 2009 Adam Ruggles.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.sapien.test.util;

import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.code.sapien.util.ClassUtils;

/**
 * Object Factory, used to build entity data models with some default set of parameters.
 * @author Adam
 * @version $Id: ObjectFactory.java 16 2009-04-12 05:05:02Z a.ruggles $
 * 
 * Created on Feb 7, 2009 at 8:36:54 PM 
 */
public final class ObjectFactory {
	/**
     * The <code>Logger</code> is used by the application to generate a log messages.
     */
    private static final Logger LOG = LoggerFactory.getLogger(ObjectFactory.class);

    /**
     * Creates a new object of type <T> and sets the values in the name/value object params.
     * @param <T> The class type.
     * @param type The class type to create a new instance of.
     * @param params A name value pair of String/Object.
     * @return A new instance of an object of type <T> or null.
     */
	@SuppressWarnings("unchecked")
	public static <T> T build(final Class<T> type, final Object... params) {
		T obj = null; 
		try {
			final Class<?> objectClass = Class.forName(type.getName(), true, ClassUtils.getClassLoader());
			obj = (T) objectClass.newInstance();
			if (params.length % 2 == 0) {
				for (int i = 0; i < params.length; i += 2) {
					if (params[i] instanceof String) {
						String name = ((String) params[i]);
						name = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
						final Object param = params[i + 1];
						final Method method = objectClass.getMethod(name, param.getClass());
						if (method != null) {
							method.invoke(obj, param);
						}
					}
				}
			} else {
				LOG.warn("Invalid set of parameters, not setting any parameters");
			}
		} catch (Exception ex) {
			LOG.error("Error occurred building object", ex);
		}
		return obj;
	}

	/**
	 * Private constructor.
	 */
	private ObjectFactory() { }
}
